package com.itheima.netty.nonblock;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;

import static com.itheima.utils.ByteBufferUtil.debugRead;

/**
 * \* Created with IntelliJ IDEA.
 * \* User: pzj
 * \* Date: 2021/11/10
 * \* Time: 11:22
 * \* Description:  NIO演示非阻塞模式
 * \
 */
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        //使用 nio 来理解阻塞模式
        final ByteBuffer buffer = ByteBuffer.allocate(16);
        //1、创建服务端
        final ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);   //设置accept非阻塞
        //2、绑定端口
        ssc.bind(new InetSocketAddress(8080));

        //3、接受客户端的连接  accept
        ArrayList<SocketChannel> channels = new ArrayList<>();
        while (true){
            //socketChannel 用来与客户端通信
            SocketChannel sc = ssc.accept();    //不会阻塞，如果没有连接，返回null
            if (sc != null){
                log.debug("connected...{}",sc);
                sc.configureBlocking(false);    //设置read非阻塞
                channels.add(sc);

            }
            for (SocketChannel channel : channels) {
                //4、接受客户端数据
                final int read = channel.read(buffer);//从channel中读取出数据，存入buffer中      不会阻塞    没有读到数据，read返回0
                if (read > 0){
                    buffer.flip();
                    debugRead(buffer);
                    buffer.clear();
                    log.debug("after read...{}",channel);
                }
            }
        }

    }
}